import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:share_plus/share_plus.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:convert';
import 'dart:io';
import '../providers/settings_provider.dart';
import '../providers/mood_provider.dart';
import '../widgets/custom_app_bar.dart';
import '../constants/app_theme.dart';
import '../constants/app_strings.dart';

/// 设置页面
class SettingsScreen extends StatefulWidget {
  const SettingsScreen({super.key});

  @override
  State<SettingsScreen> createState() => _SettingsScreenState();
}

class _SettingsScreenState extends State<SettingsScreen> {
  bool _isExporting = false;
  bool _isClearing = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CustomAppBar(
        title: AppStrings.get('settings_title'),
      ),
      body: Consumer2<SettingsProvider, MoodProvider>(
        builder: (context, settingsProvider, moodProvider, child) {
          return ListView(
            padding: const EdgeInsets.all(16),
            children: [
              _buildSectionTitle('外观设置'),
              const SizedBox(height: 8),
              _buildThemeSection(settingsProvider),
              const SizedBox(height: 24),
              
              _buildSectionTitle('通知设置'),
              const SizedBox(height: 8),
              _buildNotificationSection(settingsProvider),
              const SizedBox(height: 24),
              
              _buildSectionTitle('数据管理'),
              const SizedBox(height: 8),
              _buildDataSection(moodProvider),
              const SizedBox(height: 24),
              
              _buildSectionTitle('隐私与安全'),
              const SizedBox(height: 8),
              _buildPrivacySection(settingsProvider),
              const SizedBox(height: 24),
              
              _buildSectionTitle('关于应用'),
              const SizedBox(height: 8),
              _buildAboutSection(),
              const SizedBox(height: 32),
            ],
          );
        },
      ),
    );
  }

  /// 构建章节标题
  Widget _buildSectionTitle(String title) {
    return Text(
      title,
      style: TextStyle(
        fontSize: 16,
        fontWeight: FontWeight.bold,
        color: AppTheme.primaryColor,
      ),
    );
  }

  /// 构建主题设置区域
  Widget _buildThemeSection(SettingsProvider settingsProvider) {
    return Card(
      elevation: 2,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        children: [
          _buildSettingTile(
            icon: Icons.palette,
            title: '深色模式',
            subtitle: '切换应用主题',
            trailing: Switch(
              value: settingsProvider.isDarkMode,
              onChanged: (value) {
                settingsProvider.setDarkMode(value);
              },
              activeColor: AppTheme.primaryColor,
            ),
          ),
          const Divider(height: 1),
          _buildSettingTile(
            icon: Icons.color_lens,
            title: '主题色彩',
            subtitle: '选择应用主色调',
            trailing: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                _buildColorOption(
                  Colors.blue,
                  settingsProvider.primaryColor == Colors.blue,
                  () => settingsProvider.setPrimaryColor(Colors.blue),
                ),
                const SizedBox(width: 8),
                _buildColorOption(
                  Colors.green,
                  settingsProvider.primaryColor == Colors.green,
                  () => settingsProvider.setPrimaryColor(Colors.green),
                ),
                const SizedBox(width: 8),
                _buildColorOption(
                  Colors.purple,
                  settingsProvider.primaryColor == Colors.purple,
                  () => settingsProvider.setPrimaryColor(Colors.purple),
                ),
                const SizedBox(width: 8),
                _buildColorOption(
                  Colors.orange,
                  settingsProvider.primaryColor == Colors.orange,
                  () => settingsProvider.setPrimaryColor(Colors.orange),
                ),
              ],
            ),
          ),
          const Divider(height: 1),
          _buildSettingTile(
            icon: Icons.text_fields,
            title: '字体大小',
            subtitle: '调整文字显示大小',
            trailing: DropdownButton<double>(
              value: settingsProvider.fontSize,
              underline: const SizedBox(),
              items: const [
                DropdownMenuItem(value: 14.0, child: Text('小')),
                DropdownMenuItem(value: 16.0, child: Text('中')),
                DropdownMenuItem(value: 18.0, child: Text('大')),
                DropdownMenuItem(value: 20.0, child: Text('特大')),
              ],
              onChanged: (value) {
                if (value != null) {
                  settingsProvider.setFontSize(value);
                }
              },
            ),
          ),
        ],
      ),
    );
  }

  /// 构建通知设置区域
  Widget _buildNotificationSection(SettingsProvider settingsProvider) {
    return Card(
      elevation: 2,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        children: [
          _buildSettingTile(
            icon: Icons.notifications,
            title: '推送通知',
            subtitle: '接收应用通知',
            trailing: Switch(
              value: settingsProvider.notificationsEnabled,
              onChanged: (value) {
                settingsProvider.setNotificationsEnabled(value);
              },
              activeColor: AppTheme.primaryColor,
            ),
          ),
          const Divider(height: 1),
          _buildSettingTile(
            icon: Icons.schedule,
            title: '每日提醒',
            subtitle: '提醒记录今日情绪',
            trailing: Switch(
              value: settingsProvider.dailyReminderEnabled,
              onChanged: settingsProvider.notificationsEnabled
                  ? (value) {
                      settingsProvider.setDailyReminderEnabled(value);
                    }
                  : null,
              activeColor: AppTheme.primaryColor,
            ),
          ),
          if (settingsProvider.dailyReminderEnabled) ...[
            const Divider(height: 1),
            _buildSettingTile(
              icon: Icons.access_time,
              title: '提醒时间',
              subtitle: _formatTime(settingsProvider.reminderTime),
              onTap: () => _selectReminderTime(settingsProvider),
              trailing: const Icon(Icons.chevron_right),
            ),
          ],
        ],
      ),
    );
  }

  /// 构建数据管理区域
  Widget _buildDataSection(MoodProvider moodProvider) {
    return Card(
      elevation: 2,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        children: [
          _buildSettingTile(
            icon: Icons.download,
            title: '导出数据',
            subtitle: '导出所有情绪记录',
            onTap: () => _exportData(moodProvider),
            trailing: _isExporting
                ? const SizedBox(
                    width: 20,
                    height: 20,
                    child: CircularProgressIndicator(strokeWidth: 2),
                  )
                : const Icon(Icons.chevron_right),
          ),
          const Divider(height: 1),
          _buildSettingTile(
            icon: Icons.backup,
            title: '备份数据',
            subtitle: '备份到云端',
            onTap: () => _backupData(moodProvider),
            trailing: const Icon(Icons.chevron_right),
          ),
          const Divider(height: 1),
          _buildSettingTile(
            icon: Icons.restore,
            title: '恢复数据',
            subtitle: '从备份恢复',
            onTap: () => _restoreData(moodProvider),
            trailing: const Icon(Icons.chevron_right),
          ),
          const Divider(height: 1),
          _buildSettingTile(
            icon: Icons.delete_forever,
            title: '清空数据',
            subtitle: '删除所有记录（不可恢复）',
            onTap: () => _clearAllData(moodProvider),
            trailing: _isClearing
                ? const SizedBox(
                    width: 20,
                    height: 20,
                    child: CircularProgressIndicator(strokeWidth: 2),
                  )
                : Icon(
                    Icons.chevron_right,
                    color: Colors.red[400],
                  ),
            titleColor: Colors.red[400],
          ),
        ],
      ),
    );
  }

  /// 构建隐私设置区域
  Widget _buildPrivacySection(SettingsProvider settingsProvider) {
    return Card(
      elevation: 2,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        children: [
          _buildSettingTile(
            icon: Icons.lock,
            title: '应用锁',
            subtitle: '使用生物识别或密码保护',
            trailing: Switch(
              value: settingsProvider.appLockEnabled,
              onChanged: (value) {
                settingsProvider.setAppLockEnabled(value);
              },
              activeColor: AppTheme.primaryColor,
            ),
          ),
          const Divider(height: 1),
          _buildSettingTile(
            icon: Icons.analytics,
            title: '数据分析',
            subtitle: '允许匿名数据分析',
            trailing: Switch(
              value: settingsProvider.analyticsEnabled,
              onChanged: (value) {
                settingsProvider.setAnalyticsEnabled(value);
              },
              activeColor: AppTheme.primaryColor,
            ),
          ),
          const Divider(height: 1),
          _buildSettingTile(
            icon: Icons.privacy_tip,
            title: '隐私政策',
            subtitle: '查看隐私政策',
            onTap: () => _showPrivacyPolicy(),
            trailing: const Icon(Icons.chevron_right),
          ),
        ],
      ),
    );
  }

  /// 构建关于区域
  Widget _buildAboutSection() {
    return Card(
      elevation: 2,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        children: [
          _buildSettingTile(
            icon: Icons.info,
            title: '应用版本',
            subtitle: '1.0.0',
            trailing: const Icon(Icons.chevron_right),
          ),
          const Divider(height: 1),
          _buildSettingTile(
            icon: Icons.help,
            title: '帮助与支持',
            subtitle: '使用指南和常见问题',
            onTap: () => _showHelp(),
            trailing: const Icon(Icons.chevron_right),
          ),
          const Divider(height: 1),
          _buildSettingTile(
            icon: Icons.feedback,
            title: '意见反馈',
            subtitle: '告诉我们您的想法',
            onTap: () => _showFeedback(),
            trailing: const Icon(Icons.chevron_right),
          ),
          const Divider(height: 1),
          _buildSettingTile(
            icon: Icons.star,
            title: '评价应用',
            subtitle: '在应用商店评价',
            onTap: () => _rateApp(),
            trailing: const Icon(Icons.chevron_right),
          ),
        ],
      ),
    );
  }

  /// 构建设置项
  Widget _buildSettingTile({
    required IconData icon,
    required String title,
    required String subtitle,
    Widget? trailing,
    VoidCallback? onTap,
    Color? titleColor,
  }) {
    return ListTile(
      leading: Icon(
        icon,
        color: titleColor ?? AppTheme.primaryColor,
      ),
      title: Text(
        title,
        style: TextStyle(
          fontWeight: FontWeight.w600,
          color: titleColor ?? AppTheme.textPrimaryColor,
        ),
      ),
      subtitle: Text(
        subtitle,
        style: TextStyle(
          color: AppTheme.textSecondaryColor,
        ),
      ),
      trailing: trailing,
      onTap: onTap,
      contentPadding: const EdgeInsets.symmetric(
        horizontal: 16,
        vertical: 4,
      ),
    );
  }

  /// 构建颜色选项
  Widget _buildColorOption(Color color, bool isSelected, VoidCallback onTap) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        width: 32,
        height: 32,
        decoration: BoxDecoration(
          color: color,
          shape: BoxShape.circle,
          border: isSelected
              ? Border.all(
                  color: AppTheme.textPrimaryColor,
                  width: 3,
                )
              : null,
        ),
        child: isSelected
            ? const Icon(
                Icons.check,
                color: Colors.white,
                size: 16,
              )
            : null,
      ),
    );
  }

  /// 格式化时间
  String _formatTime(TimeOfDay time) {
    final hour = time.hour.toString().padLeft(2, '0');
    final minute = time.minute.toString().padLeft(2, '0');
    return '$hour:$minute';
  }

  /// 选择提醒时间
  Future<void> _selectReminderTime(SettingsProvider settingsProvider) async {
    final TimeOfDay? picked = await showTimePicker(
      context: context,
      initialTime: settingsProvider.reminderTime,
    );
    
    if (picked != null) {
      settingsProvider.setReminderTime(picked);
    }
  }

  /// 导出数据
  Future<void> _exportData(MoodProvider moodProvider) async {
    if (_isExporting) return;
    
    setState(() {
      _isExporting = true;
    });
    
    try {
      final records = moodProvider.records;
      final exportData = {
        'export_date': DateTime.now().toIso8601String(),
        'total_records': records.length,
        'records': records.map((record) => record.toJson()).toList(),
      };
      
      final jsonString = const JsonEncoder.withIndent('  ').convert(exportData);
      
      final directory = await getApplicationDocumentsDirectory();
      final file = File('${directory.path}/mood_records_export.json');
      await file.writeAsString(jsonString);
      
      await Share.shareXFiles(
        [XFile(file.path)],
        text: '我的情绪记录数据导出',
      );
      
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('数据导出成功'),
            backgroundColor: Colors.green,
          ),
        );
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('导出失败: $e'),
            backgroundColor: Colors.red,
          ),
        );
      }
    } finally {
      if (mounted) {
        setState(() {
          _isExporting = false;
        });
      }
    }
  }

  /// 备份数据
  Future<void> _backupData(MoodProvider moodProvider) async {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('备份数据'),
        content: const Text('此功能需要连接云端服务，暂未实现。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  /// 恢复数据
  Future<void> _restoreData(MoodProvider moodProvider) async {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('恢复数据'),
        content: const Text('此功能需要连接云端服务，暂未实现。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  /// 清空所有数据
  Future<void> _clearAllData(MoodProvider moodProvider) async {
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('清空所有数据'),
        content: const Text(
          '此操作将删除所有情绪记录，且无法恢复。\n\n确定要继续吗？',
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(false),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () => Navigator.of(context).pop(true),
            style: TextButton.styleFrom(
              foregroundColor: Colors.red,
            ),
            child: const Text('确定删除'),
          ),
        ],
      ),
    );
    
    if (confirmed == true) {
      setState(() {
        _isClearing = true;
      });
      
      try {
        await moodProvider.clearAllRecords();
        
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(
              content: Text('所有数据已清空'),
              backgroundColor: Colors.orange,
            ),
          );
        }
      } catch (e) {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text('清空失败: $e'),
              backgroundColor: Colors.red,
            ),
          );
        }
      } finally {
        if (mounted) {
          setState(() {
            _isClearing = false;
          });
        }
      }
    }
  }

  /// 显示隐私政策
  void _showPrivacyPolicy() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('隐私政策'),
        content: const SingleChildScrollView(
          child: Text(
            '我们重视您的隐私。本应用：\n\n'
            '• 所有数据仅存储在您的设备本地\n'
            '• 不会收集或上传您的个人信息\n'
            '• 不会与第三方分享您的数据\n'
            '• 您可以随时导出或删除您的数据\n\n'
            '如有疑问，请联系我们。',
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  /// 显示帮助
  void _showHelp() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('帮助与支持'),
        content: const SingleChildScrollView(
          child: Text(
            '使用指南：\n\n'
            '1. 在首页快速记录当前情绪\n'
            '2. 点击记录按钮添加详细日记\n'
            '3. 在历史页面查看过往记录\n'
            '4. 在分析页面查看情绪趋势\n\n'
            '常见问题：\n\n'
            'Q: 如何备份数据？\n'
            'A: 使用设置中的导出功能\n\n'
            'Q: 数据安全吗？\n'
            'A: 所有数据仅存储在本地设备',
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  /// 显示反馈
  void _showFeedback() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('意见反馈'),
        content: const Text(
          '感谢您使用我们的应用！\n\n'
          '如果您有任何建议或发现了问题，\n'
          '请通过以下方式联系我们：\n\n'
          '邮箱: feedback@moodapp.com\n'
          '微信: MoodAppSupport',
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  /// 评价应用
  void _rateApp() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('评价应用'),
        content: const Text(
          '如果您喜欢这个应用，\n'
          '请在应用商店给我们评价！\n\n'
          '您的支持是我们前进的动力。',
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('稍后'),
          ),
          TextButton(
            onPressed: () {
              Navigator.of(context).pop();
              // 这里可以添加跳转到应用商店的逻辑
            },
            child: const Text('去评价'),
          ),
        ],
      ),
    );
  }
}